<template>
  <div class="emerteam">
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.team_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="success"
                   size="small"
                   plain
                   v-if="permission.team_import"
                   icon="el-icon-upload2"
                   @click="handleImport">导入
        </el-button>
        <el-button type="warning"
                   size="small"
                   plain
                   v-if="permission.team_export"
                   icon="el-icon-download"
                   @click="handleExport">导出
        </el-button>
      </template>
      <!-- 附件表格自定义 -->
      <template slot="xgfj" slot-scope="scope">
        <div class="enclosure_div" v-if="scope.row['xgfj']!=''">
          <a :href="downloadHead + scope.row['xgfj']">
            <i class="el-icon-download"></i>下载附件
          </a>
        </div>
        <div class="enclosure_div" v-else>
          -
        </div>
      </template>
      <!-- 附件表单自定义 -->
      <template slot="xgfjForm">
        <div>
          <el-upload
            action="/api/fileManager/upload/file"
            :headers="SetHeaders"
            :file-list="xgfjFileList"
            :before-upload="beforeUploadxgfj"
            :on-remove="handleRemovexgfj"
            :on-success="uploadxgfjSuccess"
          >
            <el-button size="small" type="primary">选择文件</el-button>
          </el-upload>
        </div>
      </template>

      <!-- 队伍人员信息表单自定义 -->
      <template slot="dwryxxForm">
        <div>
          <el-button
            type="primary"
            size="small"
            :disabled="dialogType === viewLabel"
            @click="addControlPerson()">
            添 加
          </el-button>
        </div>
      </template>


      <!-- 队伍人员内容表单自定义 -->
      <template slot="dwryxxContentForm">
        <div class="dwryxxContent_div">
          <avue-crud
            :option="personOption"
            :data="personData"
            ref="personCrud"
          >
            <!-- 自定义操作列：删除按钮 -->
            <template slot="menu" slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                :disabled="dialogType === viewLabel"
                @click="handleDeletePerson(scope.row, scope.index)">
                删 除
              </el-button>
            </template>

            <!-- 人员工号自定义 -->
            <template slot="rygh" slot-scope="scope">
              <el-input
                placeholder="请输入人员工号"
                v-model="scope.row['rygh']"
                clearable
                size="small">
              </el-input>
            </template>
            <!-- 人员名称自定义 -->
            <template slot="rymc" slot-scope="scope">
              <el-input
                placeholder="请输入人员名称"
                v-model="scope.row['rymc']"
                clearable
                size="small">
              </el-input>
            </template>
            <!-- 性别自定义 -->
            <template slot="ryxb" slot-scope="scope">
              <el-select
                placeholder="请选择性别"
                v-model="scope.row['ryxb']"
                clearable
                size="small">
                <el-option
                  v-for="(item, index) in getPersonSex"
                  :key="index"
                  :label="item.dictValue"
                  :value="index"
                  >
                </el-option>
              </el-select>
            </template>
            <!-- 手机号码自定义 -->
            <template slot="sjhm" slot-scope="scope">
              <el-input
                placeholder="请输入手机号码"
                v-model="scope.row['sjhm']"
                clearable
                size="small">
              </el-input>
            </template>
            <!-- 职位自定义 -->
            <template slot="zw" slot-scope="scope">
              <el-select
                placeholder="请选择职位"
                v-model="scope.row['zw']"
                clearable
                size="small">
                <el-option
                  v-for="(item, index) in getPersonzw"
                  :key="index"
                  :label="item.postName"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
          </avue-crud>
        </div>
      </template>


    </avue-crud>
    <el-dialog title="应急队伍据导入"
               append-to-body
               :visible.sync="excelBox"
               width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :show-file-list="false"
                 :upload-before="beforeUpload"
                 :upload-after="uploadAfter"
                 :upload-error="uploadError"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>

  </div>
</template>

<script>
  import {getList, getDetail, add, update, remove,getsex,getzw} from "@/api/emer/team";
  import {mapGetters} from "vuex";
  import {getDeptList} from "@/api/mmhi/major_dangerous_sources";
  import {getToken} from "@/util/auth";
  import {getFzrLinkInfo} from "@/api/mmhi/prod_unit";
  import {validateTelephone} from "@/api/mmhi/validate";

  export default {
    data() {
      return {
        uploadFailed:false,
        excelBox: false,
        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '模板上传',
              prop: 'excelFile',
              type: 'upload',
              drag: true,
              loadText: '模板上传中，请稍等',
              showFileList: false,
              span: 24,
              propsHttp: {
                res: 'data'
              },
              tip: '请上传 .xls,.xlsx 标准格式文件',
              action: "/api/emerTeam/import"
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24,
            }
          ]
        },

        getPersonSex:[],
        getPersonzw:[],
        // 管控措施
        controlPersons: [],
        personData: [],
        personOption: {
          calcHeight: 30,
          tip: false,
          index: true,
          selection: false,
          addBtn: false,
          refreshBtn: false,
          columnBtn: false,
          indexWidth: 30,
          editBtn: false,
          delBtn: false,
          menuWidth: 100,
          column: [
            {
              label: "人员工号",
              prop: "rygh",
              align:"center",
              slot:true,
              maxlength:50,
            },
            {
              label: "人员名称",
              prop: "rymc",
              align:"center",
              slot:true,
              maxlength:25,
            },
            {
              label: "人员性别",
              prop: "ryxb",
              align:"center",
              slot:true,
            },
            {
              label: "手机号码",
              prop: "sjhm",
              align:"center",
              slot:true,
              maxlength:11,
              rules: [{
                required: true,
                validator:validateTelephone,
                trigger: "blur"
              }]
            },
            {
              label: "职位",
              prop: "zw",
              align:"center",
              slot:true,
              maxlength:25,
            },
          ]
        },
        dialogType: "",
        viewLabel: "view",

        //附件
        xgfjFileList: [],
        downloadHead: "/api/fileManager/download/",
        SetHeaders: { "Blade-Auth": getToken() },
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "队伍名称",
              prop: "dwmc",
              align:"center",
              maxlength:50,
              search:true,
              rules: [{
                required: true,
                message: "请输入队伍名称",
                trigger: "blur"
              }]
            },
            {
              label: "队伍级别",
              prop: "dwjb",
              align:"center",
              maxlength:25,
              type:"select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_team_level",
              props: {
                label: "dictValue",
                value: "dictKey",
              },
              rules: [{
                required: true,
                message: "请输入队伍级别",
                trigger: "blur"
              }]
            },
            {
              label: "队伍负责人",
              prop: "dwfzr",
              align:"center",
              maxlength:50,
              type: "select",
              dicUrl: "/api/prodUnitManage/bladeProdUnit/getFzrList",
              props: {
                value: "realName"
              },
              rules: [{
                required: true,
                message: "请输入队伍负责人",
                trigger: "blur"
              }]
            },
            {
              label: "负责人部门",
              prop: "fzrbm",
              align:"center",
              disabled: true,
              maxlength:100,
            },
            {
              label: "负责人手机",
              prop: "fzrsj",
              align:"center",
              maxlength:11,
              disabled: true,
            },
            {
              label: "固定电话",
              prop: "gddh",
              align:"center",
              maxlength:25,
              rules: [{
                required: false,
                validator:validateTelephone,
                trigger: "blur"
              }]
            },
            {
              label: "队伍描述",
              prop: "dwms",
              align:"center",
              type: "textarea",
              span:24,
              maxlength:500,
              rules: [{
                required: true,
                message: "请输入队伍描述",
                trigger: "blur"
              }]
            },
            //
            {
              label: "队伍人员信息",
              prop: "dwryxx",
              align: "center",
              labelWidth:120,
              span: 24,
              hide: true,
              formslot: true
            },
            {
              label: "",
              prop: "dwryxxContent",
              align: "center",
              span: 24,
              hide: true,
              formslot: true
            },
            {
              label: "相关附件",
              prop: "xgfj",
              align:"center",
              slot:true,
              formslot:true,
              viewDisplay: false,
              rules: [{
                required: false,
                message: "请输入相关附件",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    watch: {
      'form.dwfzr':{
        handler(val){
          if(val!='' && val!=undefined && val!=null){
            getFzrLinkInfo(val).then(res=>{
              this.form.fzrbm = res.data.data[0].deptName;
              this.form.fzrsj = res.data.data[0].phone;
            });
          }
        },
        immediate: true
      }
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.team_add, false),
          viewBtn: this.vaildData(this.permission.team_view, false),
          delBtn: this.vaildData(this.permission.team_delete, false),
          editBtn: this.vaildData(this.permission.team_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {
      this.initData();
      this.getsexs();
      this.getzws()
    },
    methods: {
      // 初始化数据
      initData() {
        var tenantId = JSON.parse( localStorage.getItem("saber-tenantId") ).content;
        getDeptList(tenantId).then(res => {
          const column = this.findObject(this.option.column, "fzrbm");
          column.dicData = res.data.data;
        }).then(() => {

        });
      },
      //导出摸板
      handleTemplate() {
        window.open(`/api/emerTeam/export-template?${this.website.tokenHeader}=${getToken()}`);
      },
      // 导入前判断
      beforeUpload(file, done, loading) {
        this.uploadFailed = false;
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        const extension = testmsg === 'xls'
        const extension2 = testmsg === 'xlsx'
        if(!extension && !extension2) {
          this.$message.warning('请上传 .xls,.xlsx 标准格式文件!');
          loading()
        } else {
          done()
        }
      },
      // 导入成功后1
      uploadAfter1() {
        this.excelBox = false;
        this.$message.success("上传成功");
        this.page.currentPage = 1;
        this.onLoad(this.page);
      },
      // 导入成功后
      uploadAfter(res, done) {
        done();
        if(this.uploadFailed === true) {
          return;
        }
        this.uploadAfter1()
      },
      // 导入失败后
      uploadError(error, column) {
        console.log(error,column);
        this.uploadFailed = true;
      },
      //导出应急队伍
      handleExport() {
        this.$confirm("是否导出应急队伍数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          let dwmc = this.query.dwmc !== undefined && this.query.dwmc !== "" && this.query.dwmc !== null ? this.query.dwmc : "";
          window.open(`/api/emerTeam/export?${this.website.tokenHeader}=${getToken()}&dwmc=${dwmc}`);
        });
      },
      //打开导入弹窗
      handleImport() {
        this.excelBox = true;
      },
      // 删除管控措施
      handleDeletePerson(row, index) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.personData.splice(index, 1);
        });
      },
      // 获取性别
      getsexs() {
        getsex()
          .then(res => {
            this.getPersonSex = res.data.data;
          })
          .then(() => {
            this.onLoad(this.page);
          });
      },
      // 获取职位
      getzws() {
        getzw()
          .then(res => {
            this.getPersonzw = res.data.data;
          })
          .then(() => {
            this.onLoad(this.page);
          });
      },
      // 添加队伍人员信息
      addControlPerson() {
        this.personData.push({
          rygh: "",
          rymc: "",
          ryxb: "",
          sjhm: "",
          zw: "",
        });
      },

      /**
       * 上传附件
       */

      // 上传附件前
      beforeUploadxgfj() {
        var isLimit = this.xgfjFileList.length + 1 <= 1;
        if (!isLimit) {
          this.$message.warning("只能选择一个附件!");
        }
        return isLimit;
      },

      // 上传附件成功
      uploadxgfjSuccess(response, file, fileList) {
        if (response.code !== 200 || response.success !== true) {
          return;
        }
        this.xgfjFileList = fileList;
        this.form.xgfj = response.data.id;
        console.log(this.form.xgfj)
      },

      // 删除附件
      handleRemovexgfj(file, fileList) {
        this.xgfjFileList = fileList;
        this.form.xgfj = "";
      },
      rowSave(row, done, loading) {
        if (this.personData.length === 0) {
          this.$message.warning("请添加队伍人员!");
          loading();
          return;
        }
        var isEmpty = false;
        this.personData.forEach(item => {
          if (
            item.rygh === "" ||
            item.rygh === undefined ||
            item.rymc === "" ||
            item.rymc === undefined
          ) {
            isEmpty = true;
          }
        });
        if (isEmpty) {
          this.$message.warning("请填写正确的人员信息");
          loading();
          return;
        }
        for (let key in row) {
          if (key.indexOf("$") >= 0) {
            console.log(key)
            delete row[key];
          }
        }
        row["teamPersonList"] = [];
        this.personData.forEach(item => {
          var measure = {
            rygh: item.rygh,
            rymc: item.rymc,
            ryxb: item.ryxb,
            sjhm: item.sjhm,
            zw: item.zw,
          };
          if (item.id !== "" && item.id !== undefined) {
            measure["id"] = item.id;
          }
          row.teamPersonList.push(measure);
        });
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        if (this.personData.length === 0) {
          this.$message.warning("请添加队伍人员!");
          loading();
          return;
        }
        var isEmpty = false;
        this.personData.forEach(item => {
          if (
            item.rygh === "" ||
            item.rygh === undefined ||
            item.rymc === "" ||
            item.rymc === undefined
          ) {
            isEmpty = true;
          }
        });
        if (isEmpty) {
          this.$message.warning("请填写正确的人员信息");
          loading();
          return;
        }
        for (let key in row) {
          if (key.indexOf("$") >= 0) {
            console.log(key)
            delete row[key];
          }
        }
        row["teamPersonList"] = [];
        this.personData.forEach(item => {
          var measure = {
            rygh: item.rygh,
            rymc: item.rymc,
            ryxb: item.ryxb,
            sjhm: item.sjhm,
            zw: item.zw,
          };
          if (item.id !== "" && item.id !== undefined) {
            measure["id"] = item.id;
          }
          row.teamPersonList.push(measure);
        });
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        this.personData=[]
        this.xgfjFileList=[]
        this.dialogType = type;
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            this.personData=this.form.teamPersonList
            if (type === "edit") {
              if(JSON.stringify(this.form.bladeFile)!="{}")
              this.xgfjFileList.push({
                name: this.form.bladeFile.fileName,
                response: {
                  code: 200,
                  success: true,
                  msg: "操作成功",
                  data: this.form.bladeFile
                }
              });
            }
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style lang="scss" scpoed>
  .emerteam{
    .enclosure_div {
      a {
        font-size: 12px;
        color: #409eff;

        i {
          margin-right: 5px;
        }
      }
    }
  }

  .dwryxxContent_div {
    .avue-crud {
      .el-table__empty-block,
      .el-table__header-wrapper,
      .avue-crud__menu,
      .avue-crud__pagination {
        display: none;
      }
    }
  }


  .choose_cm_footer {
    text-align: center;
    margin-top: 15px;

    .el-button {
      width: 100px;
      height: 35px;
    }
  }
</style>
